import React, { Component } from 'react'
import {connect} from 'react-redux'

class Shop extends Component {
    allnum=()=>{
        return this.props.list.reduce((pre,val)=>{
            return pre+val.num
        },0)
    }
    allprice=()=>{
        return this.props.list.reduce((pre,val)=>{
            return pre+=val.num*val.price
        },0)
    }
    render() {
        return (
            <div className="shop-wrap">
                <p onClick={()=>{this.props.history.go(-1)}}>返回</p>
                <h2>购物车<b>{this.allnum()}</b></h2>
                {
                    this.props.list.map((item,index)=>{
                        return <dl key={item.id}>
                                    <dt><img src={item.image} alt=""/></dt>
                                    <dd>
                                        <p>{item.title}</p>
                                        <p>单价：{item.price}元</p>
                                        <p>
                                            <span onClick={()=>this.props.changenum(item.id,'-')}>-</span>
                                            <b>{item.num}</b>
                                            <span onClick={()=>this.props.changenum(item.id,'+')}>+</span>
                                        </p>
                                    </dd>
                                </dl>
                    })
                }
                <p>合计：{this.allprice()}元</p>
            </div>
        )
    }
}
let mapState=(state)=>{
    return {
        list:state.reducer.shopcar
    }
}
let mapDispatch=(dispatch)=>{
    return {
        changenum(id,count){
            dispatch({
                type:"ChangeNum",
                id,count
            })
        }
    }
}
export default connect( mapState,mapDispatch )(Shop)